package com.bnlr.lrparking.appui.sharevalue.deposit;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.bank.AddBankCardOneActivity;
import com.bnlr.lrparking.appui.paypwd.SetPayPasswordActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.event.DepositSuccessEvent;
import com.bnlr.lrparking.appui.bank.model.BankCardM;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.pwddialog.SecurityEditCompileListener;
import com.bnlr.lrparking.util.pwddialog.SecurityPasswordEditText;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by hp on 2017/8/30.
 * 提现界面
 */

public class DepositActivity extends BaseActivity {

    private ImageView img_deposit;
    private TextView tv_deposit_name,tv_deposit_card;
    private TextView tvNavTitle,tv_depoist_btn,depodit_balance,all_deposit,deposit_text,deposit_money;
    private ClearEditText ed_deposit;
    private String depoistStr="";
    private RelativeLayout rely_select_bankcard,rely_select_bank;
    private String strearningsNum="";//可提现的余额
    private TextView tv_depoist_goaddbank;
    private String isSetPay;
    private Dialog dialog;
    private BankCardM.DataBean bd;
    private AlertDialog paydialog;
    private String isRealNameAuth = "";
    private DecimalFormat df   = new DecimalFormat("######0.00");
    private SecurityPasswordEditText editSecurityCode;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deposit);
        isRealNameAuth=AppConfig.getInstance().getString("isRealNameAuth", "");
        initView();
    }

    private void initView(){
        EventBus.getDefault().register(this);//
        getBandCard();
        tvNavTitle=(TextView)findViewById(R.id.tv_nav_title);
        tvNavTitle.setText("提现");
        ed_deposit=(ClearEditText)findViewById(R.id.ed_deposit);
        ed_deposit.setSelection(ed_deposit.getText().toString().length());//将光标移至文字末尾
        tv_depoist_btn=(TextView)findViewById(R.id.tv_depoist_btn);
        rely_select_bankcard=(RelativeLayout)findViewById(R.id.rely_select_bankcard);
        img_deposit=(ImageView)findViewById(R.id.img_deposit);
        tv_deposit_name=(TextView)findViewById(R.id.tv_deposit_name);
        tv_deposit_card=(TextView)findViewById(R.id.tv_deposit_card);
        depodit_balance=(TextView)findViewById(R.id.depodit_balance);
        deposit_text = (TextView) findViewById(R.id.deposit_text);
        deposit_money = (TextView) findViewById(R.id.deposit_money);
        all_deposit=(TextView)findViewById(R.id.all_deposit);
        tv_depoist_goaddbank=(TextView)findViewById(R.id.tv_depoist_goaddbank);
        rely_select_bank=(RelativeLayout)findViewById(R.id.rely_select_bank);
        all_deposit.setOnClickListener(this);
        ed_deposit.addTextChangedListener(this);
        rely_select_bankcard.setOnClickListener(this);
        Intent intent=getIntent();
        strearningsNum= intent.getStringExtra("strearningsNum");
        depodit_balance.setText(strearningsNum);
        deposit_money.setText("¥" + df.format(Double.valueOf(Double.parseDouble(strearningsNum)/LrConstant.RATE_VALUE)));
    }

    @Override
    protected void onResume() {
        super.onResume();
        isSetPay = AppConfig.getInstance().getString("paypassword", "");
        if (Params.selectBank.equals("2")) {
            Params.selectBank = "0";
            getBandCard();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        depoistStr=ed_deposit.getText().toString();
        if (depoistStr.equals("")){
            deposit_text.setText("可用余额");
            depodit_balance.setText(strearningsNum);
            deposit_money.setText("¥" + df.format(Double.valueOf(Double.parseDouble(strearningsNum)/LrConstant.RATE_VALUE)));
            tv_depoist_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ed_deposit.setShakeAnimation();
                    ToastUtils.showShort("金额不能为空");
                }
            });

        }else {
            deposit_text.setText("提现");
            if (Double.parseDouble(depoistStr) > Double.parseDouble(strearningsNum)) {
                depoistStr = strearningsNum;
                ed_deposit.setText(depoistStr);
            }
            depodit_balance.setText(depoistStr);
            deposit_money.setText("¥" + df.format(Double.valueOf(Double.parseDouble(depoistStr)/LrConstant.RATE_VALUE)));
            tv_depoist_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Double.parseDouble(ed_deposit.getText().toString()) < LrConstant.RATE_VALUE) {
                        ToastUtils.showShort("提现值不能小于"+LrConstant.RATE_VALUE);
                        return;
                    }
                    if (bd != null) {
                        if (isSetPay.equals("1")) {
                            showPayDialog();
                        } else {
                           showDialog();
                        }
                    } else {
                        ToastUtils.showShort("请先添加银行卡");
                    }
                }
            });
        }
        ed_deposit.setSelection(ed_deposit.getText().toString().length());//将光标移至文字末尾
    }

    /**
     * 弹框提示设置支付密码
     */
    private void showDialog() {
        View view3 = View.inflate(this,
                R.layout.setting_custom_dialog, null);
        // 对话框
        dialog = new AlertDialog.Builder(this, R.style.NativeDialog)
                .create();
        dialog.show();
        dialog.getWindow().setWindowAnimations(R.style.dialog_anim_style);
        dialog.getWindow().setContentView(view3);
        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
        TextView tishi2 = (TextView) view3.findViewById(R.id.text_dialog);
        tishi2.setText("安全提示");
        TextView text_phone = (TextView) view3.findViewById(R.id.text_phone);
        text_phone.setText("您还没有支付密码，请先设置！");
        // 取消按钮
        TextView btn_Cancel2 = (TextView) view3.findViewById(R.id.cancle);
        btn_Cancel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
        // 确定按钮
        TextView btn_OK2 = (TextView) view3.findViewById(R.id.sure);
        btn_OK2.setText("设置");
        btn_OK2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startActivity(SetPayPasswordActivity.class);
                dialog = null;
            }
        });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.rely_select_bankcard:
                if (isRealNameAuth.equals("0") || isRealNameAuth.equals("")) {
                    ToastUtils.showShort("请先去身份信息验证");
                }else if (isRealNameAuth.equals("2")){
                    ToastUtils.showShort("身份信息正在审核中");
                }else if (isRealNameAuth.equals("3")){
                    ToastUtils.showShort("身份信息认证失败，请重新认证");
                }else {
                    if (bd == null) {
                        Params.selectBank = "1";
                        String realName = AppConfig.getInstance().getString("realName", "");
                        startActivity(new Intent(this, AddBankCardOneActivity.class)
                                .putExtra("real_name", realName));
                    }else {
                        Intent intent=new Intent(DepositActivity.this,SelectBankCardActivity.class);
                        startActivityForResult(intent,0);
                    }
                }

                break;
            case R.id.all_deposit:
                ed_deposit.setText(strearningsNum);
                ed_deposit.setSelection(strearningsNum.length());
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0 && resultCode == 1) {
            rely_select_bank.setVisibility(View.VISIBLE);
            tv_depoist_goaddbank.setVisibility(View.GONE);
            bd = (BankCardM.DataBean) data.getSerializableExtra("select_banks");
            tv_deposit_name.setText(bd.getBankName());
            String str=bd.getAccountNo();
            String type="";
            if (bd.getCardType() == 0) {
                type = "  借记卡";

            } else {
                type = "  信用卡";
            }
            tv_deposit_card.setText("银行尾号"+str.substring(str.length()-4,str.length()) +type);
            Glide.with(this).load(bd.getBankIconUrl()).into(img_deposit);
        }
    }
    public void showPayDialog() {
        paydialog = new AlertDialog.Builder(this).create();
        paydialog.setCanceledOnTouchOutside(false);
        paydialog.show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(editSecurityCode!=null){
                    //设置可获得焦点
                    editSecurityCode.getEditText().setFocusable(true);
                    editSecurityCode.getEditText().setFocusableInTouchMode(true);
                    //请求获得焦点
                    editSecurityCode.getEditText().requestFocus();
                    //调用系统输入法
                    InputMethodManager inputManager = (InputMethodManager) editSecurityCode.getEditText()
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editSecurityCode.getEditText(), 0);
                }
            }
        }, 200);
        Window window = paydialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        window.setContentView(R.layout.activity_input_password_dialog);
        final RelativeLayout pay_back=(RelativeLayout)window.findViewById(R.id.pay_back);
        pay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paydialog.dismiss();
            }
        });

        editSecurityCode = (SecurityPasswordEditText) window
                .findViewById(R.id.security_linear);
        editSecurityCode.setSecurityEditCompileListener(new SecurityEditCompileListener() {
            @Override
            public void onNumCompleted(String num) {
                getDeposit(num);
            }
        });
    }
    //提现
    private void getDeposit(String psw){
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "ApplyMoneyToUser");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("payPassword", psw);
            mRequest.add("ApplyMode", 0);
            mRequest.add("ReceiveAccount", bd.getAccountNo());
            mRequest.add("Mobile", bd.getMobile());
            mRequest.add("RealName", bd.getRealName());
            mRequest.add("AmountValue", ed_deposit.getText().toString());
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BaseArrayBean>(baseContext, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                            if (code.equals("1")) {
                                Intent intent = new Intent(DepositActivity.this,DepositSuccessActivity.class);
                                intent.putExtra("out_money",Integer.parseInt(ed_deposit.getText().toString()));
                                intent.putExtra("bank_name",bd.getBankName());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                intent.putExtra("deposit_time",sdf.format(new Date(System.currentTimeMillis())));
                                paydialog.dismiss();
                                startActivity(intent);
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                if (code.equals("0")){
                                    CommonUtil.showToask(baseContext, obj.getString("msg"));
                                    editSecurityCode.clearEdit();
                                    Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            if(editSecurityCode!=null){
                                                //设置可获得焦点
                                                editSecurityCode.getEditText().setFocusable(true);
                                                editSecurityCode.getEditText().setFocusableInTouchMode(true);
                                                //请求获得焦点
                                                editSecurityCode.getEditText().requestFocus();
                                                //调用系统输入法
                                                InputMethodManager inputManager = (InputMethodManager) editSecurityCode.getEditText()
                                                        .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                                                inputManager.showSoftInput(editSecurityCode.getEditText(), 0);
                                            }
                                        }
                                    }, 200);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    //银行卡列表
    private void getBandCard(){

        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            mRequest.add("action", "GetUserBank");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BankCardM>(baseContext, true, BankCardM.class) {
                        @Override
                        public void doWork(BankCardM data, String code) {
                            if (code.equals("1")) {
                                if (data.getData().size()>0) {
                                    rely_select_bank.setVisibility(View.VISIBLE);
                                    tv_depoist_goaddbank.setVisibility(View.GONE);
                                    tv_deposit_name.setText(data.getData().get(0).getBankName());
                                    String str=data.getData().get(0).getAccountNo();
                                    tv_deposit_card.setText("银行尾号"+str.substring(str.length()-4,str.length())+"  储蓄卡");
                                    Glide.with(baseContext).load(data.getData().get(0).getBankIconUrl()).into(img_deposit);
                                    bd = data.getData().get(0);
                                }else {
                                    rely_select_bank.setVisibility(View.GONE);
                                    tv_depoist_goaddbank.setVisibility(View.VISIBLE);

                                }
                            }else {
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (code.equals("1")) {
                                }else {
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBankCardSucceeEvent(DepositSuccessEvent event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
